<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/1
 * Time: 10:20
 */
/**
 * 验证码类
 */

//申明头部
header('Content-type:image/png');

class codes{
    private $img;     //画布
    private $height;  //画布的高
    private $width;   //画布的宽
    private $color;   //画布的颜色
    private $r;       //颜色r;
    private $g;       //颜色g;
    private $b;       //颜色b;
    private $num;    //验证码的个数
    private $point;  //点的个数
    private $line;   //线的个数

//    构造函数
    public function __construct($height=null,$width=null,$r=null,$g=null,$b=null,$num=null,$point=null,$line=null)
    {
        $this->height = is_null($height)?'100':$height;      //画布的高
        $this->width = is_null($width)?'200':$width;        //画布的宽
        $this->r = is_null($r)?'255':$r;                    //颜色r
        $this->g = is_null($g)?'255':$g;                    //颜色g
        $this->b = is_null($b)?'255':$b;                    //颜色b
        $this->num = is_null($num)?'4':$num;                //验证码个数
        $this->point = is_null($point)?'4000':$point;       //点的个数
        $this->line = is_null($line)?'10':$line;            //线的个数
//        创建画布
        $this->img = imagecreatetruecolor($this->width,$this->height);
//        取色
        $this->color = imagecolorallocate($this->img,$this->r,$this->g,$this->b);
//        填充
        imagefill($this->img,0,0,$this->color);
    }

//    总方法
    public function all(){
        $this->word();
        $this->point();
        $this->line();
//        输出
        imagepng($this->img);
//        释放资源
        imagedestroy($this->img);
    }

//    写字
    public function word(){
//        字符数组
        $arr = 'qwertyuioplkjhgfdsazxcvbnm0123456789QWERTYUIOPLKJHGFDSAZXCVBNM';
        for($i=0;$i<$this->num;$i++){
//            获得字符数组的长度
            $len = strlen($arr)-1;
//            设置随机下标
            $id = mt_rand(0,$len);
//            获得字符
            $text = $arr[$id];
//            设置字体的随机颜色
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
//            设置字体的x/y位置
            $x = (200/$this->num)*$i+10;
            $y = (100+40)/2;
            imagettftext($this->img,40,mt_rand(-45,45),$x,$y,$color,'./simsun.ttc',$text);
        }
    }

//    制造干扰---点
    public function point(){
        for($i=0;$i<$this->point;$i++){
//            设置随机颜色
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
//            画点
            imagesetpixel($this->img,mt_rand(0,200),mt_rand(0,100),$color);
        }
    }

    public function line(){
        for($i=0;$i<$this->line;$i++){
            // 设置随机颜色
            $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
//            画线
            imageline($this->img,mt_rand(0,200),mt_rand(0,100),mt_rand(0,200),mt_rand(0,100),$color);
        }
    }
}
$code =new codes();
$code->all();
